<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParam" ref="queryForm" :inline="true">
        <el-form-item label="卷码：">
          <el-input v-model="queryParam.code" clearable></el-input>
        </el-form-item>
        <el-form-item label="学科：">
          <el-select v-model="queryParam.subjectId">
            <el-option label="数学" value="1" />
            <el-option label="物理" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="考查：">
          <el-input v-model="queryParam.tag" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <!--用户列表区域-->
      <el-table
        v-loading="listLoading"
        :data="tableData"
        :cell-style="cellStyle"
        border
        fit
        highlight-current-row
        style="width: 100%">
        <el-table-column prop="id" label="#" width="80px"></el-table-column>
        <el-table-column
          prop="subjectId"
          label="学科"
          :formatter="subjectFormatter"
          width="80px"
        ></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="tag" label="考查"></el-table-column>
        <el-table-column prop="maxnum" label="总题" width="80px"></el-table-column>
        <el-table-column prop="selectnum" label="已选" width="80px"></el-table-column>
        <el-table-column prop="show" label="显示答案" width="80px">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.show"
              :active-value="1"
              :inactive-value="0"
              @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="80px"
          :formatter="selectFormatter"></el-table-column>
        <el-table-column
          prop="code"
          label="卷码"
          width="80px"></el-table-column>
        <el-table-column
          prop="time"
          label="创建时间"
          width="120px"></el-table-column>
        <el-table-column label="操作" align="center" width="220px">
          <template slot-scope="scope">
            <el-button v-if="scope.row.selectnum < scope.row.maxnum" size="mini" @click="selectQuestion(scope.row)">选题</el-button>
            <el-button size="mini" @click="viewPaper(scope.row)">查看</el-button>
            <el-button size="mini" type="danger" @click="deletePaper(scope.row)" class="link-left">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParam.pageIndex"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" >
      </el-pagination>
      <!--选择题目的对话框-->
      <el-dialog
        v-draggable
        title="选择题目"
        :visible.sync="addDialogVisible"
        width="60%"
        @close="addDialogClosed">
        <!--内容主体区域-->
        <div >
          <el-form :model="SelectqueryParam" ref="SelectqueryParam" :inline="true">
            <el-form-item label="题目：">
              <el-input v-model="SelectqueryParam.content" clearable></el-input>
            </el-form-item>
            <el-form-item label="标签：">
              <el-input v-model="SelectqueryParam.tag" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="selectsubmitSearch">查询</el-button>
            </el-form-item>
          </el-form>
          <el-row>
            <el-col :span="12">你当前积分：{{ userscore }}</el-col>
            <el-col :span="12">已选题积分：{{ selectsocre }}</el-col>
          </el-row>
          <el-container style="height: 500px; border: 1px solid #eee">     
              <el-main style="weight: 60%;">
                <el-table :data="selectingData" :show-header="false">
                  <el-table-column prop="content" label="题目">
                    <template slot-scope="scope">
                      <p v-html="scope.row.content"></p>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <el-checkbox class="demo-checkbox" v-model="scope.row.checked" @change="checkSelectAdd(scope.row)">加入</el-checkbox>
                    </template>
                  </el-table-column>
                </el-table>
              </el-main> 
              <el-main>
                <el-table :data="selectData" :show-header="false">
                  <el-table-column label="题目">
                    <template slot-scope="scope">
                      <p v-html="scope.row.content"></p>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <el-tooltip effect="dark" content="删除" placement="top" :enterable="false" >
                        <el-button  type="danger" @click="deleteSelect(scope.row)" icon="" size="mini">删除</el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-main>
            </el-container>
    
        </div>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="UpdateSelect">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

import { mapGetters } from "vuex";

import {
  PaperList,
  updateShowAnswer,
  deletePaper,
  QuestionList,
  updatePaperSelect
} from "@/api/examApi.js";

export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regEmail.test(value)) {
        //合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        //合法的手机号码
        return cb();
      }
      cb(new Error("手机号码格式不正确"));
    };

    return {
      //获取用户列表的参数对象
      queryParam: {
        code: 0,
        tag: "",
        subjectId: "1",
        //当前页数
        pageIndex: 1,
        //当前页数据个数
        pageSize: 10,
        auth: "",
      },
      tableData: [],
      total: 0,
      //控制添加用户的对话框的显示与隐藏
      addDialogVisible: false,
      SelectqueryParam: {
        subject: "1",
        content: "",
        tag: "",
        status: "1",
        //当前页数
        pageIndex: 1,
        //当前页数据个数
        pageSize: 100,
        auth: "",
      },
      paperid:0,
      selectItem:{
        id:null,
        content:'',
        score:0,
        checked:0
      },
      selectingData:[],
      selectData:[],
      selectsocre:0,
      //添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.search();
  },
  methods: {
    submitSearch() {
      //alert(this.queryParam.subjectId)
      //this.$message('查询!')
      this.queryParam.pageIndex = 1;
      this.search();
    },
    search() {
      let _this = this;
      // this.listLoading = true
      //alert(_this.rank)
      //alert(_this.username)   
      if (_this.rank<10){
        _this.queryParam.auth = _this.username;
      }
      //alert(JSON.stringify(_this.queryParam))
      PaperList(_this.queryParam).then((response) => {
        //alert(JSON.stringify(data))
        const re = response;
        _this.tableData = re.data;
        _this.total = re.totalrecord;
        _this.queryParam.pageIndex = re.curpage;
        _this.listLoading = false;
      });
    },
      //监听 pagesize 改变的事件
    handleSizeChange(newSize){
      //console.log(newSize)
      this.queryParam.pagesize = newSize;
      this.search()
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage){
        //console.log(newPage)
        this.queryParam.pageIndex = newPage;
        this.search()
    },
    selectQuestion(row) {
      let _this = this;
      this.addDialogVisible = true;
      //this.questionShow.loading = true
      this.paperid = row.id;
    },
    addDialogClosed(){
      let _this = this;
      this.addDialogVisible = false;
      this.selectingData = [];
      this.selectData = [];

    },
    viewPaper(row) {
      //let url = this.enumFormat(this.editUrlEnum, row.questionType)
      let url = "/exam/" + row.code;
      this.$router.push({ path: url})
      //window.open(url, "_blank");
    },
    deletePaper(row) {
      let _this = this;
      var jsData = { id: row.id };
      //alert(JSON.stringify(jsData))
      deletePaper(jsData).then((re) => {
        if (re.code === 200) {
          _this.search();
          _this.$message.success(re.message);
        } else {
          _this.$message.error(re.message);
        }
      });
    },
    userStateChanged(row) {
      let _this = this;
      var jsData = { id: row.id, show: row.show ? 1 : 0 };
      //alert(JSON.stringify(jsData))
      updateShowAnswer(jsData).then((re) => {
        if (re.code === 200) {
          _this.search()
          _this.$message.success(re.message);
        } else {
          //tableData.showanswer = !tableData.showanswer
          _this.$message.error(re.message);
        }
      });
    },
    selectsearch () {
      let _this = this;
      //alert(rank)
      //alert(username)  
      //alert(JSON.stringify(_this.SelectqueryParam))
      QuestionList(_this.SelectqueryParam).then(response => {
       // alert(JSON.stringify(response))
        const re = response   

        _this.selectingData.length = 0

        re.data.forEach((item) => {
        var selectitem = {}
        selectitem.id = item.id
        selectitem.content = item.content
        selectitem.score = item.score
        selectitem.auth = item.auth
        selectitem.checked = 0
        _this.selectingData.push(selectitem)
      })
      // _this.selectingData = re.data
       // this.total = re.totalrecord
       //this.selectqueryParam.pageIndex = re.totalpage
      })
    },
    selectsubmitSearch() {
       this.listData=[];
       //alert(this.queryParam.subjectId)
       //this.$message('查询!')
       this.selectsocre =0
       this.SelectqueryParam.pageIndex = 1
       this.selectsearch()
    },
    checkSelectAdd(row){
        //alert(row.checked)
        //alert(JSON.stringify(row))
        if (row.checked==true){
          //alert(this.username)
          if (this.username == row.auth){
            this.selectsocre += Math.ceil(row.score/2)
          }
          else{
            this.selectsocre += row.score
          }
          this.selectData.push(row)
        }
        else{
          this.deleteSelect(row)
        }
       
    },

    deleteSelect(row){
       //alert(JSON.stringify(this.selectData))
         let _this = this
         for(let index in _this.selectData){
            if(_this.selectData[index].id==row.id){
                _this.selectData.splice(index,1)
            }
        }
        for (const j of this.selectingData){
          if (j.id == row.id){
            j.checked = false
          }
        }
    },
    UpdateSelect() {
      //alert(this.paperid);
      let _this = this;
      let listData=[];
      _this.selectData.forEach((item) => {
        listData.push(item.id)
      })
      //var jsData = {id: _this.paperid,content:JSON.stringify(listData),score:_this.selectsocre,number:listData.length,auth:this.username};
      var jsData = {id: _this.paperid,content:listData,score:_this.selectsocre,number:listData.length,auth:this.username};
      alert(JSON.stringify(jsData))
      updatePaperSelect(jsData).then((re) => {
       //alert(JSON.stringify(re))
        if (re.code === 200) {
          _this.addDialogClosed()
          _this.search()
          _this.$message.success(re.message);
        } else {
          //tableData.showanswer = !tableData.showanswer
          //_this.$message.error(re.message);
        }
      }) .catch((err) => {
            //alert(JSON.stringify(err))
            this.$alert('选题出错,请联系微信号：wenxinflyliu')
          });

    },
    onSubmit() {
      //alert("search");
      this.$message("查询!");
    },
    onCancel() {
      this.$message({
        message: "cancel!",
        type: "warning",
      });
    },
    cellStyle ({row, column, rowIndex, columnIndex }) {
      if (row.status === 1 && columnIndex === 6) {
        return 'color: #0CB618'
      } else if (row.status === 0 && columnIndex === 6) {
        return 'color: #EA1B29'
      } else {
        return 'color: #1a1a1b'
      }
    },
    subjectFormatter(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "数学";
      } else if (cellValue == 2) {
        return "物理";
      }
    },
    selectFormatter(row, column, cellValue, index) {
      if (cellValue == 1) {
        return "已选题";
      } else if (cellValue == 0) {
        return "未选题";
      }
    },
  },
  computed: {
    ...mapGetters({username:"name", userscore:"score",rank:"rank" }),
  },
};
</script>

<style scoped>
.line {
  text-align: center;
}
</style>

